﻿using Microsoft.AspNetCore.Mvc;
using System.ComponentModel.DataAnnotations;
using wwl.Contract.Dtos.Requests.Rbac;
using wwl.Contract.Enums;
using wwl.Contract.Interfaces.Rbac;
using wwl.WebApi.Controllers.Common;

namespace wwl.WebApi.Controllers.Rbac
{
  /// <summary>
  /// 用户管理API控制器
  /// 继承BaseController，复用通用能力（统一响应、模型验证、身份获取）
  /// 属于权限模块（Rbac）的接口入口，负责接收前端用户相关HTTP请求，提供用户CRUD、登录、密码重置等功能
  /// </summary>
  [Route("api/[controller]")]
  public class UsersController : BaseController
  {
    private readonly IUserService _userService;

    /// <summary>
    /// 初始化用户控制器
    /// </summary>
    /// <param name="userService">用户服务接口，注入用户相关业务逻辑</param>
    public UsersController(IUserService userService)
    {
      _userService = userService;
    }

    /// <summary>
    /// 用户登录接口
    /// </summary>
    /// <param name="request">登录请求模型，包含用户名和密码</param>
    /// <returns>登录成功返回用户信息和令牌，失败返回错误信息</returns>
    [HttpPost("login")]
    public async Task<IActionResult> Login([FromBody] LoginRequest request)
    {
      if (!CheckModelState())
        return FailResult(CustomErrorCode.Param_ValidationFailed, "参数验证失败");

      try
      {
        var user = await _userService.AuthenticateAsync(request.Username, request.Password);
        return user == null
            ? FailResult(CustomErrorCode.User_WrongPassword, "用户名或密码错误")
            : SuccessResult(user, "登录成功");
      }
      catch (Exception ex)
      {
        return FailResult(CustomErrorCode.System_UnknownError, $"登录失败：{ex.Message}");
      }
    }

    /// <summary>
    /// 按ID查询用户详情接口
    /// </summary>
    /// <param name="id">用户唯一标识ID</param>
    /// <returns>用户详情DTO，包含用户名、姓名、邮箱等信息</returns>
    [HttpGet("{id}")]
    public async Task<IActionResult> GetById(string id)
    {
      var userDto = await _userService.GetByIdAsync(id);
      return userDto == null
          ? FailResult(CustomErrorCode.Resource_NotFound, $"用户 '{id}' 不存在")
          : SuccessResult(userDto, "查询成功");
    }

    /// <summary>
    /// 创建用户接口
    /// </summary>
    /// <param name="request">创建用户请求模型，包含用户基本信息</param>
    /// <returns>创建成功的用户DTO</returns>
    [HttpPost]
    public async Task<IActionResult> Create([FromBody] CreateUserRequest request)
    {
      if (!CheckModelState())
        return FailResult(CustomErrorCode.Param_ValidationFailed, "参数验证失败");

      try
      {
        var createdBy = GetCurrentUserId();
        var user = await _userService.CreateAsync(request, createdBy);
        return SuccessResult(user, "用户创建成功");
      }
      catch (Exception ex) when (ex.Message.Contains("已存在"))
      {
        return FailResult(CustomErrorCode.Business_DuplicateData, ex.Message);
      }
      catch (Exception ex)
      {
        return FailResult(CustomErrorCode.System_UnknownError, $"用户创建失败：{ex.Message}");
      }
    }

    /// <summary>
    /// 更新用户信息接口
    /// </summary>
    /// <param name="id">用户唯一标识ID</param>
    /// <param name="request">更新用户请求模型，包含待更新的用户信息</param>
    /// <returns>更新成功的用户DTO</returns>
    [HttpPut("{id}")]
    public async Task<IActionResult> Update(string id, [FromBody] UpdateUserRequest request)
    {
      if (!CheckModelState())
        return FailResult(CustomErrorCode.Param_ValidationFailed, "参数验证失败，请检查输入的用户信息是否符合要求");

      try
      {
        var updatedUserDto = await _userService.UpdateAsync(id, request);
        return SuccessResult(updatedUserDto, "用户更新成功");
      }
      catch (Exception ex) when (ex.Message.Contains("未找到"))
      {
        return FailResult(CustomErrorCode.Resource_NotFound, ex.Message);
      }
      catch (Exception ex)
      {
        return FailResult(CustomErrorCode.System_UnknownError, "用户更新失败：" + ex.Message);
      }
    }

    /// <summary>
    /// 删除用户接口
    /// </summary>
    /// <param name="id">用户唯一标识ID</param>
    /// <returns>删除成功返回提示信息，失败返回错误信息</returns>
    [HttpDelete("{id}")]
    public async Task<IActionResult> Delete(string id)
    {
      var deleteSuccess = await _userService.DeleteAsync(id);
      return deleteSuccess
          ? SuccessResult("用户删除成功")
          : FailResult(CustomErrorCode.Resource_NotFound, $"用户 '{id}' 不存在");
    }

    /// <summary>
    /// 分页查询用户列表接口
    /// </summary>
    /// <param name="request">分页查询请求模型，包含页码、页大小、筛选条件等</param>
    /// <returns>分页结果，包含用户列表和总条数</returns>
    [HttpGet]
    public async Task<IActionResult> GetPaged([FromQuery] UserPagedRequest request)
    {
      if (!CheckModelState())
        return FailResult(CustomErrorCode.Param_ValidationFailed, "参数验证失败，请检查输入的查询条件是否符合要求");

      try
      {
        var pagedResult = await _userService.GetPagedAsync(request);
        return SuccessResult(pagedResult, "用户列表查询成功");
      }
      catch (Exception ex)
      {
        return FailResult(CustomErrorCode.System_UnknownError, "用户列表查询失败：" + ex.Message);
      }
    }

    /// <summary>
    /// 重置用户密码接口
    /// </summary>
    /// <param name="id">用户唯一标识ID</param>
    /// <param name="request">重置密码请求模型，包含新密码</param>
    /// <returns>重置成功返回提示信息，失败返回错误信息</returns>
    [HttpPost("{id}/reset-password")]
    public async Task<IActionResult> ResetPassword(string id, [FromBody] ResetPasswordRequest request)
    {
      if (!CheckModelState())
        return FailResult(CustomErrorCode.Param_ValidationFailed, "参数验证失败");

      try
      {
        var success = await _userService.ResetPasswordAsync(id, request.NewPassword);
        return success
            ? SuccessResult("密码重置成功")
            : FailResult(CustomErrorCode.Resource_NotFound, $"用户 '{id}' 不存在");
      }
      catch (Exception ex)
      {
        return FailResult(CustomErrorCode.System_UnknownError, $"密码重置失败：{ex.Message}");
      }
    }
  }

  /// <summary>
  /// 登录请求模型
  /// 用于接收用户登录时的用户名和密码参数
  /// </summary>
  public class LoginRequest
  {
    /// <summary>
    /// 用户名（登录账号）
    /// </summary>
    [Required(ErrorMessage = "用户名不能为空")]
    public string Username { get; set; } = string.Empty;

    /// <summary>
    /// 密码
    /// </summary>
    [Required(ErrorMessage = "密码不能为空")]
    public string Password { get; set; } = string.Empty;
  }

  /// <summary>
  /// 重置密码请求模型
  /// 用于接收用户重置密码时的新密码参数
  /// </summary>
  public class ResetPasswordRequest
  {
    /// <summary>
    /// 新密码
    /// </summary>
    [Required(ErrorMessage = "新密码不能为空")]
    [StringLength(100, MinimumLength = 6, ErrorMessage = "密码长度必须在6-100个字符之间")]
    public string NewPassword { get; set; } = string.Empty;
  }
}